package com.ceba.test.webservice.facade;

import com.ceba.test.base.helper.SystemHelper;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import com.ceba.base.constants.FileClassConstants;
import com.ceba.base.enums.GFileContentTypeEnum;
import com.ceba.base.utils.IDSFileUtils;
import com.ceba.cebautils.IDUtils;
import com.ceba.cebautils.StringUtil;
import com.ceba.test.base.config.LogicPathUtil;
import com.ceba.test.modules.storage.logicService.StorageFileCacheManage;
import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ceba.base.helper.LoggerHelper;
import com.ceba.test.base.configs.CebaConfig;
import com.ceba.test.base.configs.CebaPathUtil;
import com.ceba.test.base.language.ResourceUtils;
import com.ceba.test.base.web.response.WebServiceResponseInfo;
import com.ceba.test.modules.admin.entity.CustomResource;
import com.ceba.test.modules.admin.entity.DirManager;
import com.ceba.test.modules.admin.entity.FTPObject;
import com.ceba.test.modules.admin.entity.GStamp;
import com.ceba.test.modules.admin.entity.ISign;
import com.ceba.test.modules.admin.entity.QfRule;
import com.ceba.test.modules.admin.helper.CustomResourceHelper;
import com.ceba.test.modules.admin.logicService.AdminLogicService;
import com.ceba.test.modules.filemanage.entity.GFile;
import com.ceba.test.modules.filemanage.logicService.FileManageLogicService;
import com.ceba.test.modules.statistic.entity.ReportSign;
import com.ceba.test.webservice.entity.CustomRuleSign;
import com.ceba.test.webservice.entity.QrCode;

import abc.ID;

import abc.util.FileHelper;
import configs.context.SpringBeans;

/**
 * 第三方调用系统配置相关业务
 * 
 * @author rong
 *
 */
public class SystemFacade {
	
	private static Logger logger = LoggerFactory.getLogger(SystemFacade.class);
	
	private AdminLogicService adminLogicService 
	= SpringBeans.getAdminLogicService("adminLogicService");
	
	
	private FileManageLogicService fileManageLogicService = SpringBeans.getFileManageLogicService("fileManageLogicService");
	
	/**
	 * 根据目录id获取目录配置信息
	 * 
	 * @return
	 */
	public DirManager getDirMangerByDirId(String Id) throws Exception {
		return adminLogicService.getDirById(Id);
	}


	/**
	 * 判断访问的客户端是否合理
	 * 
	 * @param req
	 * @return
	 */
	public boolean isIpInVisited(HttpServletRequest req) {

		if (req == null) {
			return false;
		}
		String ip = req.getRemoteAddr();
		logger.debug(ip);
		if (StringUtil.isEmptyString(CebaConfig.VISIT_IP) || StringUtil.isEmptyString(ip)) {
			return false;
		}
		if (!StringUtil.isEmptyString(CebaConfig.VISIT_IP) && CebaConfig.VISIT_IP.equals(CebaConfig.VISIT_IP_ALL)) {
			return true;
		}
		if (!CebaConfig.limitIp) {
			String[] ipA = CebaConfig.VISIT_IP.split(";");
			if (ipA.length > 0) {
				for (int i = 0; i < ipA.length; i++) {
					String a = ipA[i];
					if (!StringUtil.isEmptyString(a) && a.equals(ip)) {
						return true;
					}
				}
			}
		} else {
			if (ip.equals(CebaConfig.VISIT_IP)) {
				return true;
			}
		}
		return false;
	}

	public boolean checkFtpValid(FTPObject ftp) {
		if ("true".equals(ftp.getFtpFlag())) {
			if (StringUtil.isEmptyString(ftp.getFtpReadUser()) || StringUtil.isEmptyString(ftp.getFtpReadPwd())
					|| StringUtil.isEmptyString(ftp.getFtpReadDir())) {
				return false;
			}
			if (StringUtil.isEmptyString(ftp.getFtpWriteUser()) || StringUtil.isEmptyString(ftp.getFtpWritePwd())
					|| StringUtil.isEmptyString(ftp.getFtpWriteDir())) {
				return false;
			}
		}
		return true;
	}

	public boolean isOfficeFile(String fileName) {
		return fileName.endsWith(".doc") || fileName.endsWith(".xls") || fileName.endsWith(".ppt") ||
				fileName.endsWith(".docx") || fileName.endsWith(".xlsx") || fileName.endsWith(".pptx");
	}

	public boolean isPdfFile(String fileNameOrPath) {
		return fileNameOrPath.toLowerCase(Locale.getDefault()).endsWith(".pdf");
	}

	public WebServiceResponseInfo checkPdfFileAttr(InputStream ins) throws Exception {
		WebServiceResponseInfo info = new WebServiceResponseInfo();
		if (IDSFileUtils.checkInputFileMax(ins, CebaConfig.MAX_SIZE)) {
			info.setMessage(ResourceUtils.getMessage("MODULES_UPLOADING_DOCUMENT_SHOULD_LESS")+ CebaConfig.MAX_SIZE + "M");
			info.setCode(10);
		}

		return info;
	}

	public WebServiceResponseInfo checkPdfFileAttr(InputStream ins, Attachment pdf, String dhName) throws Exception {
		WebServiceResponseInfo info = new WebServiceResponseInfo();
		// if(!pdf.getContentType().toString().contains("pdf")){
		if (!dhName.contains(".pdf")) {
			info.setMessage(ResourceUtils.getMessage("MODULES_UPLOADED_FILE_PDF_DOCUMENT_PLEASE_REUPLOAD"));
			info.setCode(9);
			return info;
		}

		if (IDSFileUtils.checkInputFileMax(ins, CebaConfig.MAX_SIZE)) {
			info.setMessage(ResourceUtils.getMessage("MODULES_UPLOADING_DOCUMENT_SHOULD_LESS")+ CebaConfig.MAX_SIZE + "M");
			info.setCode(10);
		}
		return info;
	}

	public WebServiceResponseInfo checkPdfFileAttr(String filePath) throws Exception {
		WebServiceResponseInfo info = new WebServiceResponseInfo();

		if (!IDSFileUtils.CheckFileSize(filePath, CebaConfig.MAX_SIZE)) {
			info.setMessage(ResourceUtils.getMessage("MODULES_UPLOADING_DOCUMENT_SHOULD_LESS") + CebaConfig.MAX_SIZE + "M");
			info.setCode(10);
		}
		return info;
	}

	public void clearTmpUse() {
		fileManageLogicService.timeToEmptyTempFolder();
	}

	
	/*
	 * 根据接口ID，封装参数
	 */
	public WebServiceResponseInfo getISignByStampID(String stampId, ISign[] iSigns) {
		WebServiceResponseInfo info = new WebServiceResponseInfo();
		String dir = LogicPathUtil.getSystemUploadPath(StorageFileCacheManage.getSystemUseAddressId());
		try {
			if (!StringUtil.isEmptyString(stampId)) {
				ISign iSign = new ISign();
				GStamp gs = adminLogicService.getCorStampObjectByStampId(stampId);
				if (gs != null) {
					iSign.setStampPath(dir + gs.getFilePath());
					iSign.setImgWidth(gs.getImgWidth());
					iSign.setImgHeight(gs.getImgHeight());
					iSign.setStampX(gs.getStamp_x());
					iSign.setStampY(gs.getStamp_y());
					iSign.setMatchName(gs.getMatchName());
					iSign.setStampPage(gs.getStampPage());
				}
				iSigns[0] = iSign;
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
			info.setMessage("接口异常");
			info.setCode(100);
		}
		return info;
	}

	
	/*
	 * 根据接口ID，封装参数
	 */
	public WebServiceResponseInfo getSignPDFParamArrayBySignID(String[] iSignIds, ISign[] iSigns) {
		WebServiceResponseInfo info = new WebServiceResponseInfo();
		String dir =  LogicPathUtil.getSystemUploadPath(StorageFileCacheManage.getSystemUseAddressId());
		try {
			for (int i = 0; i < iSignIds.length; i++) {
				String id = iSignIds[i];
				if (!StringUtil.isEmptyString(id)) {
					ISign iSign = adminLogicService.getInterfaceSignById(id);
					if (iSign == null) {
						info.setCode(25);
						info.setMessage(id + ResourceUtils.getMessage("MODULES_CORRESPONDING_RECORD_DOSES_NOT_EXIST"));
						return info;
					}

					// 多签的情况，只判断最后一个规则的签章以及骑缝章是否存在
					if (i == iSignIds.length - 1) {
						info = checkStampAndWater(iSign);
						if (info.getCode() != 0) {
							return info;
						}
					}
					iSigns[i] = iSign;
				}
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
			info.setMessage(ResourceUtils.getMessage("MODULES_INTERFACE_EXCEPTION"));
			info.setCode(100);
		}
		return info;
	}

	// 判断公章水印是否存在
	public WebServiceResponseInfo checkStampAndWater(ISign iSign) throws Exception {
		WebServiceResponseInfo r = new WebServiceResponseInfo();

		// 判断公章是否存在
		if (iSign == null
				|| (iSign != null && "true".equals(iSign.getStampFlag()) && !new File(iSign.getStampPath()).exists())) {
			r.setCode(14);
			r.setMessage(ResourceUtils.getMessage("MODULES_PICTURE_PUBLIC_SEAL_NOT_EXIST"));
			logger.debug(r.getMessage());
			return r;
		}
		
		
		// 判断骑缝章
		if ((iSign != null ) && "true".equals(iSign.getQfStampFlag())) {
			GStamp gs = adminLogicService.getCorStampObjectByStampId(iSign.getQfRuleId());
			if(!new File(CebaPathUtil.getWritePicPath(gs.getFilePath())).exists()){
				r.setCode(31);
				r.setMessage(ResourceUtils.getMessage("MODULES_SEAL_PICTURE_EXIST_COVER_CHAPTER"));
				logger.debug(r.getMessage());
				return r;
			}
		
		}
		return r;
	}

	public WebServiceResponseInfo checkDirFile(String origDir, String tempDir, String saveDir, String failDir) {
		WebServiceResponseInfo r = new WebServiceResponseInfo();
		if (!new File(origDir).isDirectory()) {
			r.setCode(9);
			r.setMessage(ResourceUtils.getMessage("MODULES_DIRECTORY_SIGNED_DOES_NOT_EXIST"));
			logger.debug(r.getMessage());
		}
		if (!new File(tempDir).isDirectory()) {
			r.setCode(10);
			r.setMessage(ResourceUtils.getMessage("MODULES_CACHED_DIRECTORY_DOES_NOT_EXIST"));
			logger.debug(r.getMessage());
		}
		if (!new File(saveDir).isDirectory()) {
			r.setCode(11);
			r.setMessage(ResourceUtils.getMessage("MODULES_STORAGE_DIRECTORY_NOT_EXIST"));
			logger.debug(r.getMessage());
		}
		if (!new File(failDir).isDirectory()) {
			r.setCode(12);
			r.setMessage(ResourceUtils.getMessage("MODULES_FAILURE_DIRECTORY_NOT_EXIST"));
			logger.debug(r.getMessage());
		}
		return r;
	}

	public FTPObject getFTPObjectById(String ftpId) {
		return adminLogicService.getFTPObjectById(ftpId);
	}

	/**
	 * 请求验证
	 * 
	 * @param port
	 * @return
	 * @throws Exception
	 */
//	public boolean requestValid(String qr_server_ip_port) throws Exception {
//		return workFlowLogicService.requestValid(qr_server_ip_port);
//	}

	/**
	 * 将需要签名的文档存到g_file
	 * 
	 * @param savePath
	 * @return
	 * @throws Exception
	 */
	public String addNeedSignFileToDb(String storageId,String savePath,String loginUserId) throws Exception {
		String fileId = ID.getGuid();
		String fileName = FileHelper.getFileName(savePath, false);
		String verPath =  LogicPathUtil.getVirtualPath(storageId,savePath);
		GFile gf = GFile.createGFile(fileId, fileName, GFileContentTypeEnum.PDF.getContentType(), "", savePath,
				FileClassConstants.UPLOADTHIRDREPORT,loginUserId, StorageFileCacheManage.getSystemUseAddressId(),verPath);

		if (fileManageLogicService.addFileRecordNoDocumentText(gf)) {
			return fileId;
		}
		return null;
	}

	/**
	 * 封装customRulesSign的参数内容
	 * 
	 * @param json
	 */
	public WebServiceResponseInfo parseJsonToCusRule(String json, CustomRuleSign resouse) {
		WebServiceResponseInfo rr = new WebServiceResponseInfo();

		JSONObject object = new JSONObject(json);
		if (object.has("FILE_NAME")) {
			resouse.setFileName(object.getString("FILE_NAME"));
		}
		if (object.has("QR_URL")) {
			resouse.setQrUrl(object.getString("QR_URL"));
		}

		if (object.has("RULE_ID")) {
			resouse.setRuleID(object.getString("RULE_ID"));
		}

		if (object.has("IS_SIGN")) {
			resouse.setIsSign("true".equals(object.getString("IS_SIGN")) ? true : false);
		}
		if (object.has("IS_STAMP")) {
			resouse.setIsStamp("true".equals(object.getString("IS_STAMP")) ? true : false);
		}

		// 如果RULE_ID不为空,获取资源文件并解析封装
		if (resouse.getRuleID() != null && !"".equals(resouse.getRuleID())) {
			rr = parsePropertiesCusRule(resouse.getRuleID(), resouse);
		}

		return rr;
	}

	/**
	 * 获取文件路径
	 * 
	 */

	public String getFilePath(String InterFaceSettingPath) {
		LoggerHelper.error(new Exception("Not support in Foxconn project"), "Not support in Foxconn project");
		return null;

		/*
		String filepath;
		FileInputStream in = null;
		InputStreamReader sr = null;
		try {
			in = new FileInputStream(InterFaceSettingPath);
			sr = new InputStreamReader(in, "GB2312");
			Properties prop = new Properties();
			prop.load(sr);
			if (prop.containsKey("FouS_FilePath")) {
				filepath = prop.getProperty("FouS_FilePath");
				return filepath;
			}

		} catch (Exception e) {
			LoggerHelper.error(logger, e, "解析fous.properties文件失败");
		} finally {
			if (sr != null) {
				try {
					sr.close();
				} catch (IOException e) {
					LoggerHelper.error(logger, e, "释放文件资源失败");
				}
			}

			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					LoggerHelper.error(logger, e, "释放文件资源失败");
				}
			}
		}

		return null;
		*/
	}

	/**
	 * 
	 * @param filePath
	 *            需要解析参数的配置文件
	 * @param resouse
	 * @return
	 */
	public WebServiceResponseInfo parseJsonToCusRuleFS(String filePath, CustomRuleSign resouse) {
		WebServiceResponseInfo rr = new WebServiceResponseInfo();
		rr.setCode(26);
		rr.setMessage("Not support for Foxconn project!!!");
		return rr;

		/*
		WebServiceResponseInfo rr = new WebServiceResponseInfo();
		if (StringUtil.isEmptyString(filePath) || "".equals(filePath)) {
			rr.setCode(25);
			rr.setMessage(ResourceUtils.getMessage("MODULES_PARAMETER_CONFIGURATION_FILE_DOES_EXIST"));
			return rr;
		}

		FileInputStream in = null;
		InputStreamReader sr = null;
		try {
			in = new FileInputStream(filePath);
			sr = new InputStreamReader(in, "GB2312");
			Properties prop = new Properties();
			prop.load(sr);

			if (prop.containsKey("FILE_NEME")) {
				resouse.setFileName(prop.getProperty("FILE_NEME"));
			}

			if (prop.containsKey("QR_URL")) {
				resouse.setQrUrl(prop.getProperty("QR_URL"));
			}

			if (prop.containsKey("RULE_ID")) {
				resouse.setRuleID(prop.getProperty("RULE_ID"));
			}
			if (prop.containsKey("STAMP_PAGES")) {
				resouse.setStampPages(prop.getProperty("STAMP_PAGES"));
			}
			if (prop.containsKey("QR_PAGES")) {
				resouse.setQrPages(prop.getProperty("QR_PAGES"));
			}

			if (prop.containsKey("PIC_MACTH_NAME")) {
				resouse.setPicMatchName(prop.getProperty("PIC_MACTH_NAME"));
			 }
			
			if (prop.containsKey("IS_SIGN")) {
				resouse.setIsSign("true".equals(prop.getProperty("IS_SIGN")) ? true : false);
			}
			if (prop.containsKey("IS_STAMP")) {
				resouse.setIsStamp("true".equals(prop.getProperty("IS_STAMP")) ? true : false);
			}
			// 资质章名称
			if (prop.containsKey("CREDENTIAL_NAMES")) {
				List<GStamp> credentialNames = new ArrayList<GStamp>();
				String creNames = prop.getProperty("CREDENTIAL_NAMES");
				if (!StringUtil.isEmptyString(creNames)) {
					String[] names = creNames.split(",");
					for (int i = 0; i < names.length; i++) {
						String n = names[i];
						if (!StringUtil.isEmptyString(n)) {
							GStamp gs = adminLogicService.getStampByStampName(n, 2);
							if (gs != null) {
								credentialNames.add(gs);
							}
						}
					}
					resouse.setCredentialIds(credentialNames);
				}

			}
			// 报告章名称
			if (prop.containsKey("STAMP_NAMES")) {
				List<GStamp> stampNames = new ArrayList<GStamp>();
				String sNames = prop.getProperty("STAMP_NAMES");
				if (!StringUtil.isEmptyString(sNames)) {
					String[] names = sNames.split(",");
					for (int i = 0; i < names.length; i++) {
						String n = names[i];
						if (!StringUtil.isEmptyString(n)) {
							GStamp gs = adminLogicService.getStampByStampName(n, 1);
							if (gs != null) {
								stampNames.add(gs);
							}
						}
					}
				}
				resouse.setCorStampList(stampNames);
			}

		} catch (Exception e) {
			rr.setCode(100);
			rr.setMessage(ResourceUtils.getMessage("MODULES_PARSING_PARAMETER_PROPERTIES_FILE_FAILURE"));
			LoggerHelper.error(logger, e, "解析参数Properties文件失败");
		} finally {
			if (sr != null) {
				try {
					sr.close();
				} catch (IOException e) {
					LoggerHelper.error(logger, e, "解析参数Properties文件失败");
				}
			}

			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					LoggerHelper.error(logger, e, "解析参数Properties文件失败");
				}
			}
		}

		// 如果RULE_ID不为空,获取资源文件并解析封装
		if (resouse.getRuleID() != null && !"".equals(resouse.getRuleID())) {
			rr = parsePropertiesCusRule(resouse.getRuleID(), resouse);
		}

		return rr;
		*/
	}

	/**
	 * 解析封装资源文件
	 * 
	 * @param ruleId
	 * @param resouse
	 */

	public WebServiceResponseInfo parsePropertiesCusRule(String ruleId, CustomRuleSign resouse) {
		WebServiceResponseInfo info = new WebServiceResponseInfo();
		String Sigs[] = null;
		// 资质章id
		String CredIds[] = null;
		ISign iSign = null;
		ISign iSigns[] = null;
		String dir = LogicPathUtil.getSystemUploadPath(StorageFileCacheManage.getSystemUseAddressId());
		List<GStamp> credentialStamps = new ArrayList<GStamp>();
		// 根据ruleId获取文件路径
		String path = adminLogicService.getCusRulePath(ruleId);
		if (StringUtil.isEmptyString(path) || "".equals(path)) {
			info.setCode(25);
			info.setMessage(ResourceUtils.getMessage("MODULES_CORRESPONDING_RULE_CONFIGURATION_FILE_EXIST"));
			return info;
		}
		FileInputStream in = null;
		InputStreamReader sr = null;
		try {
			in = new FileInputStream(path);
			sr = new InputStreamReader(in, "GB2312");

			Properties prop = new Properties();
			prop.load(sr);

			if (resouse != null && resouse.getCredentialIds() == null && prop.containsKey("CREDENTIAL_IDS")) {
				String CredentialIds = prop.getProperty("CREDENTIAL_IDS");

				if (!StringUtil.isEmptyString(CredentialIds)) {
					String crIds[] = CredentialIds.split(",");
					if (crIds != null) {
						CredIds = crIds;
					} else {
						CredIds = new String[] { CredentialIds };
					}
					if (CredIds.length > 0) {
						for (int i = 0; i < CredIds.length; i++) {
							GStamp crStamp = adminLogicService.getStampById(CredIds[i]);
							if (crStamp == null) {
								info.setCode(25);
								info.setMessage(CredIds[i] + ResourceUtils.getMessage("MODULES_RECORD_CORRESPONDING_QUALIFICATION_SEAL_EXIST"));
								return info;
							}
							if (crStamp != null) {
								credentialStamps.add(crStamp);
							}
						}
						resouse.setCredentialIds(credentialStamps);
					}

				}

			}

			if (prop.containsKey("SIGN_IDS")) {
				String SignIds = prop.getProperty("SIGN_IDS");
				String SigIds[] = SignIds.split(",");
				if (SigIds != null) {
					Sigs = SigIds;
				} else {
					Sigs = new String[] { SignIds };
				}
			}

			// 若报告章列表为空，则读取规则ID
			if (null != Sigs && Sigs.length > 0) {
				iSigns = new ISign[Sigs.length];
				for (int i = 0; i < Sigs.length; i++) {
					iSign = adminLogicService.getInterfaceSignById(Sigs[i]);

					if (iSign == null) {
						info.setCode(25);
						info.setMessage(Sigs[i] + ResourceUtils.getMessage("MODULES_RECORD_CORRESPONDING_SIGNATURE_RULE_NOT_EXIST"));
						return info;
					}
					GStamp gs = adminLogicService.getCorStampObjectByStampId(iSign.getStampID());

					if (resouse != null && resouse.getCorStampList() != null
							&& resouse.getCorStampList().size() == Sigs.length) {
						gs = resouse.getCorStampList().get(i);
					}
					if (gs != null) {
						iSign.setStampPath(dir + gs.getFilePath());
						iSign.setImgWidth(gs.getImgWidth());
						iSign.setImgHeight(gs.getImgHeight());
						if (resouse.getIsSign() && !resouse.getIsStamp()) {
							iSign.setStampX("0");
							iSign.setStampY("0");
							iSign.setMatchName("");
						} else {
							iSign.setStampX(gs.getStamp_x());
							iSign.setStampY(gs.getStamp_y());
							iSign.setMatchName(gs.getMatchName());
						}
						
						if(!StringUtil.isEmptyString(resouse.getStampPages())){
							iSign.setStampPage(resouse.getStampPages());
						}else {
							iSign.setStampPage(gs.getStampPage());
						}
					}
					// 不需要报告章时，服务器模式下，签章隐藏
					if (!"true".equals(iSign.getStampFlag())) {
						iSign.setSignType(1);
						iSign.setKeyNeedRect(1);
						iSign.setRectLeft(0);
						iSign.setRectRight(0);
						iSign.setRectTop(0);
						iSign.setRectBottom(0);
						iSign.setMatchName("");
					}
					iSigns[i] = iSign;

				}
				resouse.setSigns(iSigns);
			}

			// 是否将加盖报告章的当前页，转成图片-若多个，只取第一个--1,资源文件无该属性或者--100表示不需要
			if (prop.containsKey("CHANGE_COR_STAMP_TO_PIC")) {
				resouse.setChangeCorStampTOPic(
						Integer.parseInt(StringUtil.isEmptyString(prop.getProperty("CHANGE_COR_STAMP_TO_PIC")) == false
								? prop.getProperty("CHANGE_COR_STAMP_TO_PIC") : "1"));
			}
			// 若需要二维码
			if (prop.containsKey("NEED_QR") && "true".equals(prop.getProperty("NEED_QR"))) {
				QrCode code = new QrCode();
				if (prop.containsKey("FROM_LIMS_URL_TO_QR")) {
					resouse.setFromLimsUrlToQr(prop.getProperty("FROM_LIMS_URL_TO_QR"));
				}

				if (prop.containsKey("QR_PAGE_STRATEGY")) {
					code.setQrPageStrategy(
							Integer.parseInt(StringUtil.isEmptyString(prop.getProperty("QR_PAGE_STRATEGY")) == false
									? prop.getProperty("QR_PAGE_STRATEGY") : "3"));
				}

				if (prop.containsKey("QR_PAGE")) {
					code.setQrPage(Integer.parseInt(StringUtil.isEmptyString(prop.getProperty("QR_PAGE")) == false
							? prop.getProperty("QR_PAGE") : "1"));
				}
				if (prop.containsKey("QR_MATCH_NAME")) {
					code.setQrMatchName(prop.getProperty("QR_MATCH_NAME"));
				}

				if (prop.containsKey("QR_X")) {
					code.setQrX(Integer.parseInt(StringUtil.isEmptyString(prop.getProperty("QR_X")) == false
							? prop.getProperty("QR_X") : "400"));
				}

				if (prop.containsKey("QR_Y")) {
					code.setQrY(Integer.parseInt(StringUtil.isEmptyString(prop.getProperty("QR_Y")) == false
							? prop.getProperty("QR_Y") : "500"));
				}
				if (prop.containsKey("QR_WIDTH")) {
					code.setQrWidth(Integer.parseInt(StringUtil.isEmptyString(prop.getProperty("QR_WIDTH")) == false
							? prop.getProperty("QR_WIDTH") : "100"));
				}
				if (prop.containsKey("QR_HEIGHT")) {
					code.setQrHeight(Integer.parseInt(StringUtil.isEmptyString(prop.getProperty("QR_HEIGHT")) == false
							? prop.getProperty("QR_HEIGHT") : "100"));
				}
				if (prop.containsKey("NEED_QR")) {
					code.setNeedQr(StringUtil.isEmptyString(prop.getProperty("NEED_QR")) == false
							? prop.getProperty("NEED_QR") : "true");
				}
				if (prop.containsKey("NEED_BASE64")) {
					resouse.setNeedBase64(
							StringUtil.isEmptyString(prop.getProperty("NEED_BASE64")) == true ? false : true);
				}
				resouse.setQrCode(code);
			}
		} catch (Exception e) {
			info.setCode(100);
			info.setMessage(ResourceUtils.getMessage("MODULES_PARSING_PROPERTIES_FILE_FAILURE"));
			LoggerHelper.error(logger, e, "解析Properties文件失败");
		} finally {
			if (sr != null) {
				try {
					sr.close();
				} catch (IOException e) {
					LoggerHelper.error(logger, e, "释放文件资源失败");
				}
			}

			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					LoggerHelper.error(logger, e, "释放文件资源失败");
				}
			}
		}

		return info;
	}

    
	public  GStamp getStampById(String id) throws Exception{
		return adminLogicService.getStampById(id);
	}
	
	/**
	 * 获取资源规则
	 * @param qfRuleId
	 * @return
	 */
	public  CustomResource getCustomResourceById(String qfRuleId){
		return CustomResourceHelper.getByIdCusResouse(qfRuleId);
	}
	
	//获取骑缝章规则对象
	public  QfRule getQiFengRuleById(String qfRuleId){
		return CustomResourceHelper.getQiFengRuleById(qfRuleId);
	}

	/**
	 * 接口创建统计参数时初始化，并同时创建qrcode的fileId
	 * @param fileType
	 * @param editionType
	 * @param userIp
	 * @return
	 */
	public  ReportSign packCollectStatisticParm(int fileType,int editionType,String userIp){
		ReportSign  parm = new ReportSign();
        parm.setQrCodeFileId(IDUtils.getGuid());
		parm.setFileId(parm.getQrCodeFileId());
		parm.setFileType(fileType);
		parm.setEditionType(editionType);
		parm.setCreateUserIP(userIp);
		return parm;
	}

	/**
	 * 从接口入参中获取可复制参数并复制
	 * 入参allowPdfContentCopy，true-允许 false-不允许
	 * 允许PDF内容复制 0-允许 1-不允许
	 * @param iSign
	 * @param sign
	 */
	public void setAllowPdfContentCopyFromApiParam(ISign iSign, JSONObject sign) {
		//从参数中获取是否允许可复制
		if (sign.has("allowPdfContentCopy")) {
			iSign.setAllowPdfContentCopy(sign.getBoolean("allowPdfContentCopy") ? 0:1);
		}
	}

	/**
	 * 从接口入参中获取控制Api签名时关键字没匹配上是否报错
	 * 入参noErrorNotNormalMatchApiKey，true-不报错 false-报错
	 * @param sign
	 */
	public void setNoErrorNotNormalMatchApiKeyFromApiParam(JSONObject sign) {
		//从参数中获取控制Api签名时关键字没匹配
		if (sign.has("noErrorNotNormalMatchApiKey")) {
			CebaConfig.NO_ERROR_NOT_NORMAL_MATCH_API_KEY = sign.getBoolean("noErrorNotNormalMatchApiKey");
		} else {
			CebaConfig.NO_ERROR_NOT_NORMAL_MATCH_API_KEY = CebaConfig.getMatchApiKeyOfTuvParam();
		}
	}


	/**
	 * 从接口入参中获取控制Api签名时是否添加二维码
	 * 入参allowAddQrCode，true-允许 false-不允许
	 * @param sign
	 */
	public void setAllowAddQrFromApiParam(JSONObject sign) {
		//从参数中获取控制Api签名时关键字没匹配
		if (sign.has("allowAddQrCode")) {
			CebaConfig.ADD_QR_FOR_API_KEY = sign.getBoolean("allowAddQrCode");
		} else {
			CebaConfig.ADD_QR_FOR_API_KEY = SystemHelper.canUseQR();
		}
	}
}
